<template>
  <div>
    <div class="m-school-map" ref="scatterMap" :style="{width: mapWidth, height: mapHeight}">
    </div>
    <div :style="{'background-color': '#031532',width: mapWidth, height: mapHeight ,left: mapInitLeft,top:'0px', position: 'absolute'}" v-if="maphidden!=='transparent'"></div>
    <div v-if="isShowFlag&&isSchool" @click="goTop" style="position: absolute;top: 20px;right: 20px;cursor: pointer;padding: 2px 8px;border: 1px solid #0469f1;z-index:9;border-radius: 5px;color: #00a7fe;">
      返回县级概览
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import AMapLoader from '@amap/amap-jsapi-loader'
let map = null
let myChart = null

export default {
  name: 'chart-map',

  data () {
    return {
      maphidden: 'transparent',
      mmmData: [],
      // height: '895px',
      // width: '650px',
      bgColor: 'transparent',
      colors: [
        '#657df5',
        '#ffb336',
        '#4ac7ff',
        '#2bd3bd',
        '#96e388',
        '#fecd63'
      ],
      parentJson: null,
      parentInfo: [],
      curAreaId: 410223,
      mapCode: [],
      curLabName: '全部教育',
      mapSchoolData:[],
      schoolData:{},
      mapData:{},
      isSchool:false
    }
  },
  props: {
    // mmmData: {
    //   type: Array,
    //   default: () => {
    //     return [
          // {
          //   'name': 430100,
          //   'value': [
          //     {
          //       'name': '长沙市第一中学2',
          //       'value': [113.062178, 28.370502, 8, 999]
          //     }
          //   ]
          // }]
      // }
    // },
    clickDown: {
      type: Boolean,
      default: true
    },
    mapHeight: {
      type: String,
      default: '895px'
    },
    mapWidth: {
      type: String,
      default: '650px'
    },
    mapSchool: {
      type: Function,
      default: null
    },
    styleMpId:{
      type:String,
      default:''
    },
    mapInitLeft:{
      type:String,
      default:'0px'
   },
   isShowFlag:{
     type:Boolean,
     default:false
   }
  },
  computed: {

  },

  methods: {

      initNewMap () {
      let vm = this

      AMapLoader.load({
        'key': '4daa78d371fcbec403897e8ccc0c408c',   // 申请好的Web端开发者Key，首次调用 load 时必填
        'version': '1.4.15',   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        'plugins': [],  // 插件列表
        'AMapUI': {             // 是否加载 AMapUI，缺省不加载
          'version': '1.1',   // AMapUI 缺省 1.1
          'plugins':['geo/DistrictExplorer', 'misc/PointSimplifier'],       // 需要加载的 AMapUI ui插件
        },
        'Loca':{                // 是否加载 Loca， 缺省不加载
          'version': '1.3.2'  // Loca 版本，缺省 1.3.2
        }
      }).then((AMap)=>{
        vm.maphidden = '#031532'
        vm.map = new AMap.Map(vm.$refs.scatterMap, {
          viewMode: '2D',
          // mapStyle: 'amap://styles/563ccfbe13786e73a2fcd9340a89a6d6',
          mapStyle: 'amap://styles/'+vm.styleMpId,
          // pitch: 0,
          features: ['bg', 'road','point'],
          zoom: 11,
          center: [114.144366,34.401741],
          resizeEnable: true,
          // scrollWheel:true,
          skyColor: '#031532' // '#05388f'
        })
        let map = vm.map

        let districtExplorer = new AMapUI.DistrictExplorer({
          eventSupport: true, //打开事件支持
          map: map,
        })

        // let currentAreaNode = null

        districtExplorer.on('outsideClick', function(e) {
          districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) {
            // console.log('routeFeatures', routeFeatures)
            if (vm.curAreaId !== 410223) {
              vm.loadAreaNode(410223, districtExplorer)
              console.log('21321')
              // vm.getXXSData()
            }
          }, {
            levelLimit: 2
          })
        });

        districtExplorer.on('featureClick', function(e, feature) {
          let props = feature.properties
          // 如果存在子节点
          if (vm.curAreaId === 410223) {
            // 切换聚焦区域
            vm.loadAreaNode(props.adcode, districtExplorer)
            if (vm.curAreaId !== 410223) {
              // vm.getXXSData()
            }
          }
        })


        // 创建纯文本标记
        var text = new AMap.Text({
            text:'尉氏县',
            anchor:'center', // 设置文本标记锚点
            draggable:true,
            cursor:'pointer',
            // angle:10,
            style:{
                'padding': '.75rem 1.25rem',
                'margin-bottom': '1rem',
                'border-radius': '.25rem',
                'background-color': 'rgba(000,000,000,0)',
                'width': '15rem',
                'border-width': 0,
                // 'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                'text-align': 'center',
                'font-size': '20px',
                'color': 'white',
                'font-weight':'600'
            },
            position: [114.201858,34.416037]
        });
        vm.map.add(text)
        let buildlayers = new AMap.Buildings({
          zooms: [12, 18],
          zIndex: 10
          // heightFactor: 2 // 2倍于默认高度，3D下有效
        })
        vm.map.add(buildlayers)


        vm.loadAreaNode(410223,districtExplorer)

        let pointSimplifierIns = new AMapUI.PointSimplifier({
          map: map, //所属的地图实例
          autoSetFitView: false, //禁止自动更新地图视野
          zIndex: 200,
          getPosition: function(item) {
            if (!item) {
              return null
            }
            //返回经纬度
            return item.value[0].value
          },
          getHoverTitle: function(dataItem, idx) {
            return dataItem.value[0].name
          },
          renderOptions: {
            //点的样式
            pointStyle: {
              width: vm.curAreaId === 410223 ? 5 : 5,
              height: vm.curAreaId === 410223 ? 5 : 5,
              fillStyle: '#ffea92'
            },
            //鼠标hover时的title信息
            hoverTitleStyle: {
              position: 'top'
            }
          }
        })
        vm.pointSimplifierIns = pointSimplifierIns

        vm.map.on("complete", function () {
          vm.maphidden = 'transparent'
          // distCluster.setData(dddata)
          // vm.getMapSchool().then(() => {
          let effData = []
          effData = vm.mapSchoolData

          pointSimplifierIns.setData(effData)
          //   vm.refreshNewMap(pointSimplifierIns)
          // })0
        })
        // 地图缩放时放开 返回县级概览 按钮的权限控制
        vm.map.on('zoomstart',function(){
          vm.isSchool=true
        })
        // 地图拖拽时放开 返回县级概览 按钮的权限控制
        vm.map.on('dragstart',function(){
          vm.isSchool=true
        })
        vm.map.on('zoomend', function () {
          vm.refreshNewMap(pointSimplifierIns)
        })
        // 14
        pointSimplifierIns.on('pointClick', function (e, p) {
          vm.map.setZoomAndCenter('13', e.originalEvent.lnglat)
          vm.getSchoolData(p.data)
        })

      }) // 结束
    },
    refreshNewMap (pointSimplifierIns) {
      let vm = this
      let zoom = vm.map.getZoom()
      //获取 pointStyle
      let pointStyle = pointSimplifierIns.getRenderOptions().pointStyle
      // pointStyle.fillStyle = vm.effectcolor
      //根据当前zoom调整点的尺寸
      if (zoom >= 13) {
        pointStyle.width = pointStyle.height = 8
      } else {
        pointStyle.width = pointStyle.height = 5
      }
    },
    loadAreaNode (adcode, districtExplorer) {
      let vm = this
      let colors = ['#1890ff', '#ffb686', '#ffe666', '#11c9aa', '#a694ff', '#fb6c84', '#91dcf2', '#91dcf2']
      if (vm.curAreaId === adcode && vm.curAreaId !== 410223) {
        return
      }
      vm.curAreaId = adcode
      districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
        //更新地图视野
        // vm.map.setBounds(areaNode.getBounds(), null, null, true)
        //清除已有的绘制内容
        districtExplorer.clearFeaturePolygons()
        //绘制父区域
        districtExplorer.renderParentFeature(areaNode, {
          cursor: 'default',
          bubble: true,
          strokeColor: '#88d2ff', //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 1, //线宽
          fillColor: vm.curAreaId === 410223 ? '#0114c6' : '#657df5', //填充色
          fillOpacity: 0.35, //填充透明度
          // fillOpacity: 1, //填充透明度
        })
        districtExplorer.setAreaNodesForLocating([areaNode])
      })
    },
    // 返回县级概览
    goTop(){
      this.map.setZoomAndCenter('11', [114.144366,34.401741])
      if(this.isShowFlag){
        this.$emit('mapschool')
        this.map.setZoomAndCenter(11,[114.144366,34.401741])
        this.isSchool=false
      }
    },
    // 根据返回学校定位点调用获取学校信息
    getSchoolData (params) {
      if(this.isShowFlag){
        this.$emit('mapschool',params)
        this.isSchool=true
      }
      this.mapData = params.mapdata
      this.schoolData.name = params.name
      this.schoolData.schoolshow = true
      // this.$emit('input', this.mapData.jgid)
      // this.$emit('change', this.mapData.jgid)
      // this.getVideoList(this.mapData.jgid)
    },
    getSchoolDW(queryData='全部教育'){
      let newListCond= []

      newListCond= [ {fieldName: 'tjnf',operator: 'IN', fieldValues: ['2019'],prepender: 'AND'}]
      if(queryData!=='全部教育'){
        newListCond= [ {fieldName: 'tjnf',operator: 'IN', fieldValues: ['2019'],prepender: 'AND'},{ 'fieldName': 'jyjd', 'fieldValues': [queryData], 'operator': 'IN', 'prepender': 'AND' }]
      }
      let data = {
        'pagination': {
          'calTotal': true,
          'numPerPage': 1000,
          'pageNo': 1,
          'start': 0,
          'startNum': -1
        },
        conditions: newListCond
      }
      this.$axios.post(`/tw-cloud-datatheme-server/themedata/app_xxxx_xxwzxx`, data).then(res=>{
        let {pageInfo, serverResult} = res.data
        if(serverResult.resultCode==='200'){
          let dataset=[]
          // dataset=pageInfo.list.map(el=>{
          //   return  {
          //         'name': el.xxmc,
          //         'value': [el.wd,el.jd]
          //   }
          // })
          dataset=pageInfo.list.map(el=>{
            return   {
              'name': 410223,
              'value': [
                {
                  'name': el.xxmc,
                  'value': [el.wd,el.jd],
                  'jgid':el.jgid
                }
              ]
            }
          })
          this.mapSchoolData=dataset
          this.initNewMap()
        }
      })
    }
  },

  mounted () {
    this.getSchoolDW()
    let vm = this
    this.$nextTick(() => {
      // vm.searchCity(330400)
      vm.initNewMap()
    })

    // window.addEventListener('resize', this.resize)
  },

  beforeDestroy () {
    if (myChart) {
      myChart.dispose()
      myChart = null
    }
    if (map) {
      map.destroy()
      map = null
    }
    // window.removeEventListener('resize', this.resize)
  }
}
</script>

<style lang="scss">
 .tw-datasetchart {
  width: 100%;
  height: 600px;
}

.tw-datasetchart-chartbox {
  display: block;
  width: 100%;
  height: 100%;
}

.m-school-map {
  // background-color: transparent !important;
}
</style>
